package com.mediastory.spsserver.apns.service.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javapns.Push;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.mediastory.spsserver.apns.dao.ApnsDao;
import com.mediastory.spsserver.apns.domain.Apns;
import com.mediastory.spsserver.apns.service.ApnsSvc;

@Service
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT ,rollbackFor = {Exception.class} ,readOnly = false)
public class ApnsSvcImpl implements ApnsSvc {

	@Autowired
	ApnsDao apnsDao;
	
	@Autowired
	private MessageSourceAccessor messages;
	
	public ApnsSvcImpl() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public List<Apns> findbyList(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		return (List<Apns>) (apnsDao.SelectList(condition));
	}

	public Map<String, Object> findbyListPaging(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("apnsList", (List<Apns>) (apnsDao.SelectList(condition)));
		resultMap.put("apnsListTotalCnt", (Integer) (apnsDao.SelectListTotalCnt(condition)));
		
		return resultMap;
	}

	@Override
	public Apns findby(Integer id) throws Exception {
		// TODO Auto-generated method stub
		return apnsDao.select(id);
	}

	@Override
	public Apns add(Apns apns) throws Exception {
		// TODO Auto-generated method stub
		Apns result = apnsDao.insert(apns);
		
		return result;
	}

	@Override
	public Apns modify(Apns apns) throws Exception {
		// TODO Auto-generated method stub
		return apnsDao.update(apns);
	}

	@Override
	public int remove(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return apnsDao.delete(condition);
	}
	
	@Override
	public void push() throws Exception {
		// TODO Auto-generated method stub
		
		//운영일 때 true, 개발일 때 false
		boolean production = true;
		/* Decide how many threads you want to create and use */ 
        int threads = 30;

		String msg = "";
		
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("push", 1);
		List<Apns> apnsList = (List<Apns>) (apnsDao.SelectList(condition));
		
		List<String> devices = null;
		Apns apnsCon = null;

		for (Apns apns : apnsList) {
			msg = apns.getMsg();
			String gubun = apns.getGubun();
			Object keystore = "";
			String password = "";
			
			/* *
			 * 구분 값
			 * e : 에스콰이어
			 * h : 하퍼스바자
			 * m : 모터트렌드
			 * t : APNS테스트
			 * */
			/*
			if(gubun.equals("e")){
				keystore = "D:/esquire_dist.p12";
				password = "q1w2e3r4";
			}else if(gubun.equals("h")){
				keystore = "D:/bazaar_dist.p12";
				password = "q1w2e3r4";
			}else if(gubun.equals("m")){
				keystore = "D:/motor_dist.p12";
				password = "q1w2e3r4";
			}else if(gubun.equals("t")){
				keystore = "D:/motor_dist.p12";
				password = "q1w2e3r4";
			}else{
				continue;
			}
			*/
			
			if(gubun.equals("n")){
				keystore = messages.getMessage("apns.keystore");
				password = messages.getMessage("apns.password");
			}else{
				continue;
			}

			//apns 하는 기기의 token 값 조회
			devices = (List<String>)(apnsDao.selectListDeviceToken(gubun));
			
			/* Prepare a simple payload to push */ 
			PushNotificationPayload payload = PushNotificationPayload.alert(msg);
			payload.addBadge(1);

	        /* Start threads, wait for them, and get a list of all pushed notifications */ 
	        List<PushedNotification> notifications = Push.payload(payload, keystore, password, production, threads, devices);
	        
	        //apns 보내는 목록 로깅
			//File logText = new File("D:/upload/kaya_apns/log_"+ Integer.toString(apns.getId()) +".txt");
	        File logText = new File(messages.getMessage("apns.logsDir") + "log_"+ Integer.toString(apns.getId()) +".txt");
			Writer fileWriter = new FileWriter(logText); 
			BufferedWriter writer = new BufferedWriter(fileWriter);
			writer.write("msg : " + apns.getMsg());
			writer.newLine();
	        
			List<PushedNotification> successfulNotification = PushedNotification.findSuccessfulNotifications(notifications);
			writer.write("success : " + successfulNotification.size());
			writer.newLine();
			
			List<PushedNotification> failedNotifications = PushedNotification.findFailedNotifications(notifications);
			writer.write("fail : " + failedNotifications.size());
			writer.newLine();
			
	        for (String device : devices) {
	        	//System.out.println(pushedNotification);
	        	writer.write("device : "+ device);
	        	writer.newLine();
			}

			writer.close();

	        //apns 상태값 변경
	        apnsCon = new Apns();
	        apnsCon.setId(apns.getId());
	        apnsCon.setStatus(1);
	        apnsCon.setPushTime("1");
	        apnsCon.setPushCnt(devices.size());
	        apnsDao.update(apnsCon);
		}
		
	}

}